package 多线程.Test;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author kirito
 * @Date 2024/1/4 14:23
 * @PackageName:多线程.Test
 * @ClassName: Test08
 * @Description:
 * @Version 1.0
 */
public class Test08 {
    private static Map<Integer, Integer> map = new ConcurrentHashMap();
    private static Lock lock = new ReentrantLock(true);
    private static int state = 0;
    public static void main(String[] args) throws InterruptedException {
        A a = new A();
        B b = new B();
        C c = new C();
        a.start();
        b.start();
        c.start();
        //踩坑，继承线程重写run方法后，然后a.run()
        //导致只能只能开启一个线程，bc就无法启动，应该用start
        //如果直接run，走的是重写的run方法，就无法启动bc
//        a.run();

        map.put(1, 1);
    }
    static class A extends Thread{

        @Override
        public void run() {
                /*lock.lock();
                为什么lock.lock()不能放在for循环外边，
                因为这样会导致加锁后，一直在判断while，然后又不成立，因为没有释放锁让其他线程获取锁
                所以会导致一直卡在B又无法输出
                for (int i = 0; i < 10; ) {
                    while (state % 3 == 0) {
                        System.out.println("A");
                        i++;
                        state++;
                    }
                }*/
            for (int i = 0; i < 10;) {
                try {
                    lock.lock();
                    while (state % 3 == 0) {
                        System.out.println("A");
                        i++;
                        state++;
                    }
                }finally {
                    lock.unlock();
                }
            }
        }
    }
    static class B extends Thread{

        @Override
        public void run() {
            for (int i = 0; i < 10;) {
                try {
                    lock.lock();
                    while (state % 3 == 1) {
                        System.out.println("B");
                        i++;
                        state++;
                    }
                }finally {
                    lock.unlock();
                }
            }
        }
    }
    static class C extends Thread{

        @Override
        public void run() {
            for (int i = 0; i < 10;) {
                try {
                    lock.lock();
                    while (state % 3 == 2) {
                        System.out.println("C");
                        System.out.println("--------");
                        i++;
                        state++;
                    }
                }finally {
                    lock.unlock();
                }
            }
        }
    }
}
